<template>
  <div class="chart-component" :style="backgroundStyle">
    <ChartTitle :title-config="info.titleConfig || {}" />
    <div style="height:260px;background-color:#fff">用于占位</div>
    <div ref="lineChartRef" class="chart-canvas line-chart-canvas"></div>
  </div>
</template>

<script>
import echarts from 'echarts';
import { debounce } from '../../untils/commonUtils';
import computedBackgroundStyle from './supplement/computedBackgroundStyle';
import ChartTitle from './supplement/ChartTitle.vue'
export default {
  name: 'LineChart',
  props: {
    info: {
      type: Object,
      default: () => ({}),
    }
  },
  data(){
    return{
      lineChart:null,
      defaultOptions: {
        grid: {
          left: 60,
          top: 60,
          right: 60,
          bottom: 60,
          containLabel: true,
        },
        legend: {
          data: ['最高气温', '最低气温'],
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        },
        yAxis: {
          type: 'value',
          splitLine: {
            show: false,
          },
          axisLabel: {
            formatter: '{value} °C',
          },
        },
        series: [
          {
            name: '最高气温',
            type: 'line',
            data: [10, 11, 13, 11, 12, 12, 9],
          },
          {
            name: '最低气温',
            type: 'line',
            data: [1, -2, 2, 5, 3, 2, 0],
          },
        ],
      }
    }
  },
  computed: {
    backgroundStyle(){
      return computedBackgroundStyle(this.info);
    },
    grid(){
      return this.info.grid || this.defaultOptions.grid;
    },
    legend(){
      return this.info.legend || this.defaultOptions.legend;
    },
    xAxis(){
      return this.info.xAxis || this.defaultOptions.xAxis
    },
    yAxis(){
      return this.info.yAxis || this.defaultOptions.yAxis
    },
    options(){
      return {
        ...this.defaultOptions,
        legend: { ...this.defaultOptions.legend, ...this.legend },
        grid: { ...this.grid },
        xAxis: { ...this.defaultOptions.xAxis, ...this.xAxis },
        yAxis: { ...this.yAxis},
      };
    }
  },
  mounted(){
    console.log("line-info:",this.info);
    console.log("backgroundStyle",this.backgroundStyle);
    this.createChart();
  },
  methods:{
    createChart(){
      if (this.$refs.lineChartRef) {
        console.log("创建图表",this.options);
        this.lineChart = echarts.init(this.$refs.lineChartRef);
        this.lineChart.setOption(this.options);
      }
    },
    debounceRerender(){
      debounce(() => {
        if (this.lineChart) {
          this.lineChart.dispose();
          this.lineChart = null;
        }
        createChart();
      }, 200)
    }
  },
  watch:{
    info:{
      handler(newVal, oldVal) {
        this.debounceRerender();
      },
      deep: true,
      immediate: true
    }
  },
  components: {
    ChartTitle
  }
}
</script>
